<?php
/**
 * Created by PhpStorm.
 * User: dell
 * Date: 2019/4/22
 * Time: 15:36
 */
namespace Modules\ApiV2\Controllers;

use App\Models\Address;
use App\Models\Coupon;
use App\Models\ExchangeRecord;
use App\Models\RechargeOrder;
use App\Models\User;
use App\Models\UserCoupon;
use Carbon\Carbon;
use function GuzzleHttp\Psr7\str;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Modules\Token\Facades\Token;

class LabourController extends BaseController {

    public function isEnd(){
        $startDate = "2019-02-26 00:00:00";
        $endDate = "2019-05-20 23:59:59";
        if (strtotime($startDate)>time()) {
            $data = ["status"=>2,"status_text"=>"未开始"];
        }elseif (strtotime($endDate)>=$endDate){
            $data = ["status"=>1,"status_text"=>"进行中"];
        }else{
            $data = ["status"=>0,"status_text"=>"已结束"];
        }
        return $this->success(["data"=>$data]);
    }

    //活动兑换
    public function activityExchange(Request $request){
        try {
            $mealId = $request->input("meal",false);
            if (!$mealId)return self::fail(1003,"缺少必要参数:meal");
            $addressId = $request->input("address_id");
            //查询收货地址
            $addressData = Address::find($addressId);

            //获取用户Id
            $userId = Token::data("id");
            $user = User::find($userId);
            if (!$user) return self::fail(1014,"用户不存在");
            //活动开始时间和结束时间
            $startDate = '2019-02-26';
            $endDate = '2019-05-20';
            if (strtotime($startDate) > time()) return self::fail(1032,"亲,活动还未开始!");
            if (strtotime($endDate) < time()) return self::fail(1033,"亲,活动已结束了!");
            //查询活动期间用户的累计金额
            $data = RechargeOrder::where("user_id", $userId)->where("months",">=",3)->whereDate("paid_at", '>=', $startDate)->whereDate("paid_at", "<=", $endDate)->select("recharge_amount","months")->get();
            $sumMoney = 0;
            foreach ($data as $item){
                $sumMoney += $item->recharge_amount*$item->months;
            }
            //查询活动期间已兑换的金额
            $exchargeMoney = ExchangeRecord::where("user_id", $userId)->sum('money');
            //计算累计金额
            $money = $sumMoney-$exchargeMoney;
            //转换金额
            if ($mealId==1){
                $minAmount = 5000;
                $coupon_id = 20;
            }elseif ($mealId==2){
                $minAmount = 10000;
                $coupon_id = 21;
            }else{
                $minAmount = 20000;
                $coupon_id = 22;
            }
            if ($money<$minAmount){
                return self::fail(1034,"亲!您的累计金额不足哟!");
            }
            //查询优惠券
            $couponData = Coupon::find($coupon_id);
            if (!$couponData)return self::fail(1016,"优惠券不存在");
            //计算过期时间
            if ($couponData->expire_type==1) {
                $time = time() + ($couponData->expire_days * 24 * 60 * 60);
                //过期时间
                $finished_at = date('Y-m-d H:i:s', $time);
            }else{
                $finished_at = $couponData->finished_at;
            }

            DB::beginTransaction();
            //实例化对象
            $excharge = new ExchangeRecord();
            $excharge->user_id = $userId;
            $excharge->money = $minAmount;
            $excharge->coupon_id = $coupon_id;
            //查询vip卡送出张数
            $exchangeVIPCount = ExchangeRecord::where("money",20000)->count();
            if ($mealId==3 && $exchangeVIPCount<50){
                $excharge->other_goods = "金汇通航VIP个人贵宾卡";
            }
            if ($addressData) {
                $excharge->username = $addressData['username'];
                $excharge->phone = $addressData['phone'];
                $excharge->address = str_replace(',', '', $addressData['city']) . $addressData['address'];
            }
            $excharge->save();

            UserCoupon::sendCouponToUser($couponData->id,$userId);
            DB::commit();
            return self::success();
        }catch (\Exception $e){
            Log::error($e);
            DB::rollBack();
            return self::fail(500,"系统错误");
        }
    }

    //累计金额
    public function accumulateAmount(){
        try{
            $userId = Token::data("id");
            $userData = User::find($userId);
            if (!$userData)return self::fail(1014,"用户不存在");
            //活动开始时间和结束时间
            $startDate = '2019-02-26';
            $endDate = '2019-05-20';
            if (strtotime($startDate) > time()) return self::fail(1032,"亲,活动还未开始!");
            if (strtotime($endDate) < time()) return self::fail(1033,"亲,活动已结束了!");
            //查询活动期间用户的累计金额
            $data = RechargeOrder::where("user_id", $userId)->where("months",">=",3)->whereDate("paid_at", '>=', $startDate)->whereDate("paid_at", "<=", $endDate)->select("recharge_amount","months")->get();
            $sumMoney = 0;
            foreach ($data as $item){
                $sumMoney += $item->recharge_amount*$item->months;
            }
            //查询活动期间已兑换的金额
            $exchargeMoney = ExchangeRecord::where("user_id", $userId)->sum('money');
            //计算累计金额
            $money = $sumMoney-$exchargeMoney;
            return self::success(["amount"=>$money]);
        }catch (\Exception $e){
            Log::error($e);
            return self::fail(500,"系统异常");
        }
    }
}